using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using mvc.Models;
using mvc.Requst;
using mvc.RE;
namespace mvc.Controllers
{
    public class ProductController:Controller
    {
        

        public IActionResult Index(){

            var Category =new EFR<Category>();
            var table1=Category.Table.FirstOrDefault();
            if (table1==null)
            {
                Category.Insert(new Category{
                    CategoryName = "生活类"
                });
            }          
            
              var product = new EFR<Product>();
            var table2 = product.Table.Where(x => x.IsDeleted == false).ToList();
            return View(table2);

        }

        public IActionResult CreateOrEdit(int id)
        {
            if (id == 0)
            {

                return View();
            }
            else
            {
                var product = new EFR<Product>();
                var table = product.Table.FirstOrDefault(x => x.IsDeleted == false && x.Id == id);
                return View(table);
            }
        }
        public IActionResult Save(ProductRequst res)
        {
            var product = new EFR<Product>();
            if (res.Id == 0)
            {
                product.Insert(new Product
                {
                    ProductName = res.ProductName,
                    Price = res.Price,
                    Stock = res.Stock,
                    Supplier = res.Supplier,
                    CategoryId = 1
                });
            }
            else
            {
                var table = product.Table.FirstOrDefault(x => x.IsDeleted == false && x.Id == res.Id);
                table.ProductName = res.ProductName;
                table.Price = res.Price;
                table.Stock = res.Stock;
                table.Supplier = res.Supplier;
                product.Update(table);
            }
            return Ok();
        }
        public IActionResult Delete(int id)
        {
            var product = new EFR<Product>();
            product.Delete(id);
            return RedirectToAction("Index");
        }
        public IActionResult Query(TextRequst res)
        {
            var product = new EFR<Product>();
            var text=res.Text!=null?res.Text.Trim():"";
            var table=product.Table.Where(x=>x.IsDeleted==false).ToList();
            if(text.Length>0){
                table=product.Table.Where(x=>x.IsDeleted==false&& x.ProductName.Contains(text)).ToList();
            }
            return Json(table);
        }

    }
}
